package com.liyasong.cf;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.common.LongPrimitiveIterator;
import org.apache.mahout.cf.taste.impl.recommender.CachingRecommender;
import org.apache.mahout.cf.taste.impl.recommender.GenericItemBasedRecommender;
import org.apache.mahout.cf.taste.impl.similarity.file.FileItemSimilarity;
import org.apache.mahout.cf.taste.model.DataModel;
import org.apache.mahout.cf.taste.recommender.RecommendedItem;
import org.apache.mahout.cf.taste.recommender.Recommender;
import org.apache.mahout.cf.taste.similarity.ItemSimilarity;


public class MyItemBasedRecommender {

	private static int recommendNum = 8;
	private static String recommendFile = "bookRecommendFile.txt";
	
	private static Date time;
	private static DateFormat df = DateFormat.getTimeInstance();
	private static int count = 0;
	
	public static void main(String[] args) throws IOException, TasteException {
		
		DataModel dataModel = MyDataModel.bookSmallData();
	
		ItemSimilarity itemSimilarity = new FileItemSimilarity(MyDataModel.bookSimData());
		
		Recommender recommender = new GenericItemBasedRecommender(dataModel, itemSimilarity);
		
		Recommender cachingRecommender = new CachingRecommender(recommender);
		
		System.out.println("程序开始运行：");
		
		long start = System.currentTimeMillis();
		BufferedWriter bw = new BufferedWriter(new FileWriter(recommendFile));
		LongPrimitiveIterator users = dataModel.getUserIDs();
	
		for (Iterator<Long> iterator = users; iterator.hasNext();) {
			long uid = iterator.next();
			List<RecommendedItem> recommendation = cachingRecommender.recommend(uid, recommendNum);
			
			for (RecommendedItem recommendedItem : recommendation) {
				bw.write(uid + "," + recommendedItem.getItemID() + 
						"," + recommendedItem.getValue() + "\n");
			}
			if ((count++)%50 == 0) {
				time = new Date();
				System.out.println(df.format(time)+"给第"+count+"个用户已经推荐");
			}
		}

		/*
		
		for (long uid = 3646; uid < 6041; uid++) {

			List<RecommendedItem> recommendation = cachingRecommender.recommend(uid, recommendNum);

			for (RecommendedItem recommendedItem : recommendation) {
				bw.write(uid + "," + recommendedItem.getItemID() + 
						"," + recommendedItem.getValue() + "\n");
			}

			if ((count++)%50 == 0) {
				time = new Date();
				System.out.println(df.format(time)+"给第"+count+"个用户已经推荐");
			}
		}
		*/
		
		bw.close();
		
		long end = System.currentTimeMillis();
		System.out.println("对131436个用户推荐图书共耗时："+(end-start)/60000+"分钟");

	}

}
